import Canvas from "canvas";
import OSS from "ali-oss";
import Path from "path";
import Log from "./Log.js";
// import Config from "../config.js";

// 字体清单
const resourceFonts = {};
// 正在加载的图片
const resourceImages = {};

// 获取图片链接
const getImageSrc = (url, option = {}) => {
    const type = /^(simple|print)$/.test(option.type) ? option.type : "print";
    const form = option.form || "anyway";

    if (!url) {
        return ""; // url为空，直接返回域名
    } else if (/^https?:\/\//.test(url)) {
        return url; // 有域名
    } else if (/^blob:/.test(url)) {
        return url; // blob数据，肯定不对了
    } else if (/^data:image\//.test(url)) {
        return url; // base64数据
    } else if (type == "simple" && form == "materials") {
        // 缩略图
        // return url.replace(/\.(png|jpe?g|gif)$/i, '-litimg.$1')
        return url;
    } else {
        return url;
    }
};

// 获取客户端
const getOssClient = () => {
    // // 环境变量
    // const variable = (( process.env.npm_lifecycle_script || "").match(/NODE_ENV=(\w+)/) || [])[1];
    // // id
    // const accesskeyid = 'LTAI5tPDh76mNr4hJQSCoiMg';
    // // secret
    // const accesskeysecret = '1iNcABGorRHMZgJYspwUwiR16XX4vt';
    // // 存储桶 所在地区
    // const regionid = variable == 'development' ? 'oss-us-east-1' : 'oss-us-east-1-internal';
    // // 存储桶
    // const defaultbucket = 'pod-product';

    return new OSS({
        accessKeyId: Config.accessKeyId,
        accessKeySecret: Config.accessKeySecret,
        region: Config.region,
        bucket: Config.bucket,
    });
};

// 加载资源
export const loadImage = (url, opt) => {
    const imageSrc = getImageSrc(url, opt);
    const imagesItem = resourceImages[imageSrc];

    if (!imageSrc) {
        // 没有图片
        Log.error("路径图片为空:" + url);
        return Promise.reject("Image url is empty, url:" + url);
    } else if (imagesItem && imagesItem.status == "complete") {
        // 已经有图片了，加载已完成
        return Promise.resolve(imagesItem.image);
    } else if (imagesItem && imagesItem.status == "loading") {
        // 加载中的
        return new Promise((resolve, reject) => {
            imagesItem.callback.push(err => {
                if (imagesItem.image) {
                    resolve(imagesItem.image);
                } else {
                    reject(err);
                }
            });
        });
    } else {
        return new Promise((resolve, reject) => {
            // 没有图片
            // 或是图片加载失败

            const limit = 1; // 失败尝试次数
            const loader = {
                count: 1, // 加载次数
                image: null,
                src: imageSrc,
                // expired: new Date().getTime() + 3600000, // 过期时间
                status: "loading",
                callback: [],
            };

            const getImageOssUrl = url => {
                if (!url) {
                    // url为空，直接返回域名
                    return Promise.reject("url is empty");
                } else if (/^https?:\/\//.test(url)) {
                    // 有域名
                    return Promise.resolve(encodeURI(url));
                } else if (/^blob:/.test(url)) {
                    // blob数据
                    return Promise.resolve(url);
                } else if (/^data:image\//.test(url)) {
                    return Promise.resolve(url);
                } else {
                    return new Promise((resolve, reject) => {
                        try {
                            getOssClient()
                                .get(url)
                                .then(result => resolve(result))
                                .catch(e => reject(e));
                        } catch (e) {
                            // statements
                            reject(e);
                        }
                    });

                    // return getOssClient().get(url).then(result=>Promise.resolve(result.content))
                }
            };

            const createImage = () => {
                // 这里要用阿里云对象存储来做
                getImageOssUrl(loader.src)
                    .then(result => {
                        return new Promise((resolve, reject) => {
                            const img = new Canvas.Image();
                            img.onload = () => resolve(img);
                            img.onerror = err => reject(err);
                            img.crossOrigin = "anonymous";
                            img.src = result.content;
                            img.size = result.res.size;
                        });
                    })
                    .then(image => {
                        // 成功
                        loader.image = image;
                        loader.status = "complete";
                        loader.callback.map(cb => cb(image));
                        loader.callback = [];
                        delete resourceImages[imageSrc];
                    })
                    .catch(error => {
                        // 失败
                        loader.count += 1;
                        if (loader.count > limit) {
                            // 加载多次都失败了
                            if (error.code == "NoSuchKey") {
                                Log.error("未找到图片: " + loader.src);
                                loader.callback.map(cb => cb("Image not found: " + loader.src));
                            } else {
                                Log.error("加载图片失败: " + loader.src);
                                loader.callback.map(cb => cb("Failed to load image: " + loader.src));
                            }
                            loader.status = "error";

                            loader.callback = [];
                            delete resourceImages[imageSrc];
                        } else if (error.code == "NoSuchKey" && /-litimg\.(png|jpe?g|gif)$/i.test(loader.src)) {
                            // 缩略图没找到加载原图
                            loader.src = loader.src.replace(/-litimg\.(png|jpe?g|gif)$/i, ".$1");
                            setTimeout(createImage, 100);
                        } else {
                            setTimeout(createImage, 100);
                        }
                    });
            };

            loader.callback.push(err => {
                if (loader.image) {
                    resolve(loader.image);
                } else {
                    reject(err);
                }
            });

            resourceImages[imageSrc] = loader;
            createImage();
        });
    }
};

// 获取图片路径
export const loadFont = (name, canvas) => {
    const fontFamily = name || "Arial";
    const fontPath = [
        { name: "Arial", url: "/fonts/Arial.ttf" },
        { name: "Space Age", url: "/fonts/Space-Age.woff" },
        { name: "Bebas Neue", url: "/fonts/Bebas-Neue.woff" },
        { name: "Circle", url: "/fonts/Circle.woff" },
        { name: "Doodle Pen", url: "/fonts/Doodle-Pen.woff" },
        { name: "Game On", url: "/fonts/Game-On.woff" },
        { name: "KG Happy", url: "/fonts/KGHAPPY.ttf" },
        { name: "Lcd", url: "/fonts/Lcd.woff" },
        { name: "Miss Stanfort", url: "/fonts/Miss-Stanfort.woff" },
        { name: "UniDream LED Regular", url: "/fonts/UniDream-LED-Regular.woff" },
    ];

    const fontItem = resourceFonts[fontFamily];
    const fontActive = fontPath.filter(i => i.name == fontFamily)[0];

    if (!fontActive) {
        return Promise.reject("unknown font family :" + fontFamily);
    } else if (fontItem && fontItem.status == "complete") {
        // 已经有图片了，加载已完成
        return Promise.resolve(fontItem);
    } else if (fontItem && fontItem.status == "loading") {
        // 加载中的
        return new Promise((resolve, reject) => {
            fontItem.callback.push(err => {
                if (fontItem.status == "complete") {
                    resolve(fontItem);
                } else {
                    reject(err);
                }
            });
        });
    } else {
        return new Promise((resolve, reject) => {
            // 没有图片
            // 或是图片加载失败
            const loader = {
                count: 10, // 加载次数
                name: fontActive.name,
                expired: new Date().getTime() + 3600000,
                uri: Path.resolve() + "/src" + fontActive.url,
                status: "loading",
                callback: [],
            };

            // 添加文字
            const createFont = () => {
                try {
                    // 有个问题
                    // 字体加载要在 new Fabric.StaticCanvas 之前 ，要不加载不出来
                    Canvas.registerFont(loader.uri, { family: loader.name });

                    // Fabric.nodeCanvas.registerFont(loading.uri, {
                    //     family: loader.name,
                    //     weight: 'regular',
                    //     style: 'normal'
                    // })

                    // var font = new Fabric.nodeCanvas.Font(loader.name, loader.uri);
                    // font.addFace(__dirname + '/fonts/Ubuntu-Bold.ttf', 'bold');
                    // font.addFace(__dirname + '/fonts/Ubuntu-Italic.ttf', 'normal', 'italic');
                    // font.addFace(__dirname + '/fonts/Ubuntu-BoldItalic.ttf', 'bold', 'italic');

                    // Canvas.contextContainer.addFont(font);  // when using createPNGStream or createJPEGStream
                    loader.status = "complete";
                    loader.callback.map(cb => cb(loader));
                    loader.callback = [];
                    delete resourceFonts[name];
                } catch (err) {
                    // 加载多次都失败了
                    loader.status = "error";
                    loader.callback.map(cb => cb(err));
                    loader.callback = [];
                    delete resourceFonts[name];
                }
            };

            loader.callback.push(err => {
                if (loader.status == "complete") {
                    resolve(loader);
                } else {
                    reject(err);
                }
            });

            resourceFonts[name] = loader;
            createFont();
        });
    }
};

// 加载设计面的所有字体
export const loadFontByLayers = layers => {
    // 字体要先加载
    const fonts = {};
    const promises = [];

    layers.map(item => {
        if (item.type != "text") {
            // 不是文字
        } else if (!item.font_family) {
            // 没有字体
        } else if (fonts[item.font_family]) {
            // 已经有了
        } else {
            fonts[item.font_family] = true;
            promises.push(loadFont(item.font_family));
        }
    });

    return Promise.all(promises);
};

// 根据设计信息获取资源
export const loadResource = piece => {
    // 圈层
    const layers = (piece || {}).layers || [];

    // 异步请求
    const promises = [];

    // 循环图层
    layers.map(item => {
        if (item.type == "text") {
            // 文字
            item.font_family && promises.push(loadFont(item.font_family));
        } else if (item.type == "image") {
            // 图片
            item.url && promises.push(loadImage(item.url));
        }
    });

    if (promises.length > 0) {
        return Promise.all(promises);
    } else {
        return Promise.resolve();
    }
};

// 加载本地图片
export const loadLocalImage = async path => {
    return Canvas.loadImage(path);
};
